﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GOFconsole
{
    public class Chapter25_Mediator
    {
        public void MediatorTest()
        {
            ConcreteMediator m = new ConcreteMediator();
            //让两个具体同事类认识中介者对象
            ConcreteColleague1 c1 = new ConcreteColleague1(m);
            ConcreteColleague2 c2 = new ConcreteColleague2(m);
            //让中介者认识两个具体的同事对象
            m.Colleague1 = c1;
            m.Colleague2 = c2;
            //同事对象的发送信息都是中介者转发的
            c1.Send("吃饭了吗？");
            c2.Send("没呢，你请客吗？");

        }
    }

    abstract class Mediator //抽象中介者
    {
        //定义一个抽象的发送消息方法，得到同事对象和发送信息
        public abstract void Send(string message, Colleague colleague);
    }
    abstract class Colleague //抽象同事类
    {
        protected Mediator mediator;
        public Colleague(Mediator mediator) //构造方法，得到中介者对象
        {
            this.mediator = mediator;
        }
    }

    class ConcreteMediator : Mediator   //具体中介者类
    {
        private ConcreteColleague1 colleague1;
        private ConcreteColleague2 colleague2;

        public ConcreteColleague1 Colleague1
        { 
            set { colleague1 = value; } 
        }
        public ConcreteColleague2 Colleague2 
        {
            set { colleague2=value; }
        }

        public override void Send(string message, Colleague colleague)
        {
            if (colleague == colleague1)
            {
                colleague2.Notify(message);
            }
            else
            {
                colleague1.Notify(message);
            }
        }
    }
    class ConcreteColleague1 : Colleague
    {
        public ConcreteColleague1(Mediator mediator)
            : base(mediator)
        { }

        public void Send(string message)    //发送信息是通过中介者发送出去的
        {
            mediator.Send(message, this);
        }

        public void Notify(string message)
        {
            Console.WriteLine("同事1得到信息："+message);
        }
    }
    class ConcreteColleague2 : Colleague
    {
        public ConcreteColleague2(Mediator mediator)
            : base(mediator)
        { }

        public void Send(string message)    //发送信息是通过中介者发送出去的
        {
            mediator.Send(message, this);
        }

        public void Notify(string message)
        {
            Console.WriteLine("同事2得到信息：" + message);
        }
    }
}
